﻿using Duende.IdentityServer.Models;
using Duende.IdentityServer.ResponseHandling;
using Duende.IdentityServer.Services;
using Duende.IdentityServer.Stores;
using Duende.IdentityServer.Validation;
using IdentityModel;
using Microsoft.AspNetCore.Authentication;
using Simple.Tools;
using SimpleSaas.Web.Common;
using SimpleSaas.Web.Common.redis;

namespace SimpleSaasAuth.Configuration
{
	public class CustomTokenReponseGenerator : TokenResponseGenerator
	{

		private readonly IRedisClientService _redisCache;

		private readonly string strWeixing = "weixinopen";
		private ILogger<TokenResponseGenerator> logger;
		public CustomTokenReponseGenerator(ISystemClock clock, ITokenService tokenService,
		   IRefreshTokenService refreshTokenService, IScopeParser scopeParser, IResourceStore
		   resources, IClientStore clients, ILogger<TokenResponseGenerator> _logger, IRedisClientService redisClientService) : base(clock, tokenService, refreshTokenService, scopeParser, resources, clients, _logger)
		{
			//_redisCache = cache;
			logger = _logger;
			this._redisCache = redisClientService;
		}

		/// <summary>
		/// 生成token
		/// </summary>
		/// <param name="request"></param>
		/// <returns></returns>
		public override async Task<TokenResponse> ProcessAsync(TokenRequestValidationResult request)
		{
			var tokenResponse = new TokenResponse();

			string key = string.Empty;
			var _claim = request.ValidatedRequest.Subject?.FindFirst(e => e.Type == "sub");
			if (SimpleCheck.IsNotNull(_claim))
			{
				key = _claim.Value;
#if DEBUG
				logger.LogInformation(key);
#endif
			}

			if (request.ValidatedRequest.GrantType == strWeixing || OidcConstants.GrantTypes.Password == request.ValidatedRequest.GrantType)
			{
				//通过账号密码登录 或者微信登录
				#region
				if (SimpleCheck.IsNull(request.CustomResponse["code"]))
				{
					tokenResponse.Custom.Add("code", "400");
					return tokenResponse;
				}
				if (request.CustomResponse["code"].ToString() != "200")
				{
					tokenResponse.Custom = request.CustomResponse;
					return tokenResponse;
				}

				#endregion

				if (request.ValidatedRequest.GrantType == strWeixing)
				{
					tokenResponse = await ProcessExtensionGrantRequestAsync(request);
				}
				else if (OidcConstants.GrantTypes.Password == request.ValidatedRequest.GrantType)
				{
					tokenResponse = await ProcessPasswordRequestAsync(request);
				}

				else if (OidcConstants.GrantTypes.ClientCredentials == request.ValidatedRequest.GrantType)
				{
					//
					tokenResponse = await ProcessClientCredentialsRequestAsync(request);
				}
				else if (OidcConstants.GrantTypes.AuthorizationCode == request.ValidatedRequest.GrantType)
				{
					tokenResponse = await ProcessAuthorizationCodeRequestAsync(request);
				}
				else if (OidcConstants.GrantTypes.RefreshToken == request.ValidatedRequest.GrantType)
				{
					//刷新，获取新的token 删除老的token
					tokenResponse = await ProcessRefreshTokenRequestAsync(request);
				}

				//加入缓存
				if (!string.IsNullOrEmpty(tokenResponse.AccessToken))
				{
					TokenInfo tokenInfo = new TokenInfo();
					tokenInfo.ExprieTime = DateTime.Now.AddMilliseconds(86400);
					tokenInfo.AccessToken = tokenResponse.AccessToken;
					tokenInfo.RefreshToken = tokenResponse.RefreshToken;
					tokenInfo.SetRefeshTokenExprieTime();
					await this._redisCache.SetAsync($"seq:user:accesstoken:{key}", tokenInfo, 86400);
				}
			}
			return tokenResponse;
		}
	}
}